A Study of the Data Provided by the Donors Choose Organization

by Steve Henle Hazel John Jim Schlough

Overview and Motivation:

Funding the contemporary K-12 classroom is greatly challenging and many teachers believe that resources provided are insufficient in meeting the most basic objectives. Nontraditional support is playing an increasingly important part in supporting the modern classroom.

The Donors Choose web platform provides a mechanism of providing support to teachers by benefactors. A potential donor may read an appeal written by a teacher to fulfill a specific classroom material need, and donates towards their funding goal. If the funding goal is met, these materials are sourced by fulfillment sources under the control of the Donors Choose organization, and sent directly to the school.

Given the changes in public sentiments and commitments towards financial support of the community school over the past few decades, the ability to raise funds directly into the classroom might come to be considered a vital skill of the teacher in supporting classroom activities.

When written appeals succeed by becoming fully funded, or fail by expiring, the data surrounding the appeal is gathered and made publicly available. By analyzing this data, it might be possible to better understand the factors correlated with success or failure of a written appeal. Some factors such as location, date and time, and poverty level are beyond the control of a teacher. Other factors, such as the written content of an appeal, or to a lesser extent, the credentials of the teacher, can be controlled.

We wish to apply statistical analysis of the available data in an effort to go beyond axiomatic and aesthetic beliefs regarding what makes a more or less effective funding proposal.

back to top

Initial Questions:

We set forth to answer the following questions regarding the funding proposals for Donors Choose.

What makes the difference between a proposal that is funded and one that expires?
Which are the winning qualities?
Of the predicting qualities, are there any that are under the control of the writer?
Does the content of the written essay matter?

back to top

Data:

We are using the data made publicly available on the Donors Choose website. This publicly available comes in the form of downloadable csv files, ranging in size from megabytes to gigabytes. This data can be found at here.

The proposals are one element in the open data set published from the Donors Choose web site. An image of the schema showing the suggested recomposition is in Appendix B, below, and can also be found at Donors Choose.
back to top

Data Wrangling

back to top

Step 1: Data Download & Cleanup

Our first task was to download the data, clean it up and extract the data we needed. We decided to do the analysis with just the data from 2014, so the final task was the filter out unneeded data.

back to top

rm_old: Our First Data Wrangling Utility

Our first plan was to use a combination of AWK and SED to do the necessary data cleanup, but time & date fields proved to be problematic. After an evening of steady efforts along those lines, a C++ data cleaning application was written as a stop gap measure. This C++ data cleaner provided a temporary means to separate the 2014 projects records from the csv file and get the rest of the team started with the data. The source code for the intermediate c++ application, was named rm_old and its source code can be found here in Appendix A.

back to top

Data Loader Redone in R

The c++ application made with the source code above was disadvantageous in that it would only run on Macintosh computers, used by 2 out of 3 group members. So this solution was set aside, in favor of the solution written in R, with source found in Appendix C, so everyone could run the same dataloader.

We also saved the final data sets to submit as part of the project.

This is only run once and not evaluated after that since we can read data from the filtered data files directly.

back to top

Step 2: Data Upload from disk

This is where we would start after the initial data retrieval. We need to load the data from the RDS files in the data folder

# Create function to load data from the rds files containing the
# name "kind".
uploadData <- function(kind) {
  temp <- list.files(path = "./data", 
                    pattern = paste0(".*", kind, ".*rds.gz"),
                    full.names = TRUE)
  # Read in the data
  tables <- lapply(temp, read_rds)
  
  # Combine multiple (or single) dataframes into one and return
  return (bind_rows(tables))
}

# Read in the different data sets
projects <- uploadData("projects")
resources <- uploadData("resources")
donations <- uploadData("donations")
essays <- uploadData("essays")

back to top

Exploratory Analysis:

We began an exploration of the data to see what relationships might be discovered within it, to compare the completed and expired projects.

## [1] "Data is nowhere near normal, looks like logistic analysis of funded vs non-funded make much more sense."
## [1] "Will not look at different factors contained in the projects file to determine if they affect the likliehood of getting funded. There are techinically three outcomes for each request. Complete, means reached or succeeded funding goal. Expired, time ran out wihtout reaching goal. Reallocated, Did not reach goal, but donors chose to give previously pledge amount to a different proposal."

## Warning: Removed 6 rows containing non-finite values (stat_smooth).

Building a Prediction Model for Proposal Success

The first attempt to build a model was to use the glm method in the train function and select several variables from the earlier exploratory analysis that looked to have an effect. These variables included: amount of money asked for, school state, primary focus, primary subject, resource type, date posted. We used glm because our outcome is either funded or not funded and glm works well for logistic regression.

#create column for binary 1 = funded, 0 = not funded regression
projects <- projects %>% mutate(funded = ifelse(funding_status == "completed", 1 , 0))

fit_selected_components <- train(funded ~ total_price_excluding_optional_support + primary_focus_area + school_charter + primary_focus_subject + students_reached + school_state + resource_type + date_posted,  data=projects, method="glm", family="binomial")

fit_selected_components
## Generalized Linear Model 
## 
## 170326 samples
##     45 predictor
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 170320, 170320, 170320, 170320, 170320, 170320, ... 
## Resampling results:
## 
##   RMSE       Rsquared  
##   0.4395598  0.09204762
## 
## 

The RMSE from this method is not great, but it is a start so we tried to improve on it. First we filtered out some of the uncommon variables, that appeared to have an effect in the exploratory analysis. For example if the teacher was in teacher in teach for America, a New York teach fellow, was it a charter school, or other school types. All total these only filtered out few percent of the applications, and are factors the requesters can’t change so they are not useful in building a prediction model. We then ran the training again.

#fliter out less used variables
projects2 <- projects %>% filter(school_year_round == 'f'& school_magnet == 'f'& school_charter == 'f'& school_nlns == 'f'& school_kipp == 'f'& school_charter_ready_promise == 'f'& teacher_teach_for_america == 'f'& teacher_ny_teaching_fellow == 'f')

#run train again
fit_selected_components_filtered <- train(funded ~ total_price_excluding_optional_support + primary_focus_area + primary_focus_subject + students_reached + school_state + resource_type + date_posted,  data=projects2, method="glm", family="binomial")

fit_selected_components_filtered
## Generalized Linear Model 
## 
## 133860 samples
##     45 predictor
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 133855, 133855, 133855, 133855, 133855, 133855, ... 
## Resampling results:
## 
##   RMSE       Rsquared  
##   0.4431695  0.09205148
## 
## 

Removing these proposals did show an effect in an improvement of RMSE, even though it is . The next approach was that perhaps our model was trying to fit to many parameters, so we pared it down to only include the factors that the exploratory analysis showed to have the greatest effect. These factors were: cost, date of posting, and resource type.

#run train again using most selective variables
fit_more_selective_components <- train(funded ~ total_price_excluding_optional_support +  date_posted + resource_type,  data=projects2, method="glm", family="binomial")

fit_more_selective_components
## Generalized Linear Model 
## 
## 133860 samples
##     45 predictor
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 133860, 133860, 133860, 133860, 133860, 133860, ... 
## Resampling results:
## 
##   RMSE       Rsquared  
##   0.4467338  0.07661878
## 
## 

This shows an even greater improvement in RMSE. In looking back at the data it was clear that the cost requested has the strongest effect. So we decided to run train again to see if that variable alone might improve our accurary (as shown by RMSE).

fit_cost_only <- train(funded ~ total_price_excluding_optional_support,  data=projects2, method="glm", family="binomial")

fit_cost_only
## Generalized Linear Model 
## 
## 133860 samples
##     45 predictor
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 133860, 133860, 133860, 133860, 133860, 133860, ... 
## Resampling results:
## 
##   RMSE       Rsquared  
##   0.4480187  0.07175816
## 
## 

So using all the data, except the contents of the essay, provided by the requesters it appears that the best model we can build is using the total cost as a predictor.

back to top

Text Analysis

Word Selection Analysis
# Tokenize the essay and remove stop words and include only
# all alphabetic words. All words are lower case, so there is
# no need to transform
essays_tokenized <- essays %>%
  select(`_projectid`, `_teacherid`, essay) %>%
  unnest_tokens(essay_words,essay)  %>%
  filter(!essay_words %in% stop_words$word &
           grepl("^[[:alpha:]]*$", essay_words))

# Get the sentiment lexicon from mrc
nrc <- sentiments %>%
  filter(lexicon == "nrc") %>%
  select(word, sentiment)

# Assign sentiments to words
essays_sentiments <- essays_tokenized %>%
  left_join(nrc, by = c("essay_words" = "word"))

# Include the funding_status of the projects
essays_sentiments <- essays_sentiments %>%
  left_join(projects, by = "_projectid") %>%
  select(`_projectid`, funding_status, essay_words, sentiment)

# Count the sentiment frequency
essays_sentiment_freq <-
  essays_sentiments %>%
  group_by(funding_status, sentiment) %>%
  summarise(sentiment_freq = n()) %>%
  group_by(funding_status) %>%
  mutate(occurance_pct = sentiment_freq*100/sum(sentiment_freq)) %>%
  ungroup()


# Plot the sentiment frequency and seperate by funding status
essays_sentiment_freq %>%
  filter(funding_status != "reallocated") %>%
  ggplot(aes(x=sentiment, y = occurance_pct, fill = sentiment)) +
  geom_bar(stat="identity") +
  facet_grid(~funding_status) +
  theme(text = element_text(size = 10),
        title = element_text(size = 12),
        legend.key.size = unit(0.5, "cm"),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
  ggtitle('Sentiment Occurance% in Funding Essays') +
  coord_flip()

# Compute word frequency in essays regardless of sentiment
# or funding_status
essays_word_freq <-
  essays_sentiments %>%
  group_by(essay_words) %>%
  summarise(completed_freq = sum(funding_status == "completed"),
            expired_freq = sum(funding_status == "expired"))

# Plot the top 10 words for both funding status
p1 <- essays_word_freq %>%
  top_n(n=10, wt=completed_freq) %>%
  ggplot(aes(x=reorder(essay_words, completed_freq),
             y = log10(completed_freq))) +
  geom_bar(stat="identity", fill = "blue") +
  ggtitle('Top 10 Words (completed)') +
  theme(axis.text = element_text(size = 8),
        axis.title = element_text(size = 10),
        plot.title = element_text(size = 10)) +
  xlab("essay_words") +
  coord_flip()

p2 <- essays_word_freq %>%
  top_n(n=10, wt=expired_freq) %>%
  ggplot(aes(x=reorder(essay_words, expired_freq), 
             y = log10(expired_freq))) +
  geom_bar(stat="identity",  fill = "green") +
  ggtitle('Top 10 Words (expired)') +
  theme(axis.text = element_text(size = 8),
        axis.title = element_text(size = 10),
        plot.title = element_text(size = 10)) +
  xlab("essay_words") +
  coord_flip()

grid.arrange(p1, p2, nrow=1)

# Students stands out for both "completed" and "expired" projects,
# So create word clouds without it, to see the rest better
essays_word_freq <- essays_word_freq %>%
  filter(essay_words != "students")

# Create word cloud for funded essays
wordcloud(essays_word_freq$essay_words, essays_word_freq$completed_freq,
          min.freq = 10000, max.words=100, random.order=TRUE,
          rot.per=0.35, colors=brewer.pal(8, "Dark2"))

# Create word cloud for expired essays
wordcloud(essays_word_freq$essay_words, essays_word_freq$expired_freq,
          min.freq = 10000, max.words=100, random.order=TRUE,
          rot.per=0.35, colors=brewer.pal(8, "Dark2"))

back to top

Essay Length Analysis: Comparing the word count for completed vs expired projects

Essay Word Counts
project_count_2014 170326
completed_project_count_2014 118039
completed_project_mean_word_count 302
completed_project_sd_word 84
expired_project_count_2014 51246
expd_total_word_sums_count 51245
expd_total_word_sums_mean 305
expd_total_word_sums_sd 86

back to top

Essay word count comparison results

Does essay word count matter?

Here we look at the number of words in essays, to see if there is any significant difference between the number of words in completed and expired essays.

## [1] "On average, completed essays had essay word counts that were 2.9918 shorter than expired ones"

The length of essay, in terms of word count, does not seem to matter much all by itself.

back to top

Final Analysis:

After examining the data, we were able to draw some conclusions. Of all of the predictors, the total project cost was found to the be most significant.

Appendices

Appendix A: rm_old Source Code

The original source code of the stop gap c++ data cleaning application is below.

####c++ Source code for rm_old

//
//  main.cpp
//  rm_old
//
//  Created by Jim Schlough on 4/22/16.
//  Copyright © 2016 Jim Schlough. All rights reserved.
//

#include <iostream>
#include <fstream>    // for ifstream, ofstream

#include <string>
#include <ctime>
#include <cstdlib>
#include <stdio.h>    // for tmpnam, remove

// for time & date processing:
#include <sstream>
#include <locale>
#include <iomanip>

using namespace std;

int main(int argc, const char * argv[]) {

    // insert code here...
    if (argc< 3 )
    {
        std::cout << "Usage rm_old fileInName bottomCutOffDate topCutOffDate dateFieldIndex" << endl;
        std::cout << endl;
        std::cout << "   dateFieldIndex is ONE based" << endl;
    }
    
    char filebuf [L_tmpnam];
    ::strcpy(filebuf, argv[1]);
    
    std::string outFileName;

    int dateFieldIdx = 0;
    dateFieldIdx = std::atoi(argv[4])-2;
    
    
    // TODO: check for clean cutOffDateInput here
    int64_t bottomCutOffDateValue = 0L, topCutOffDateValue = 0L;
    bottomCutOffDateValue = std::atol(argv[2]);
    topCutOffDateValue = std::atol(argv[3]);
    
    // TODO: check for valid (positive integer) date field index (1 based) here
    

    std::ifstream inputFile (filebuf, std::ios::in);
    outFileName.append(filebuf);
    outFileName.erase( outFileName.find(".csv"),4);
    outFileName.append("_output.csv");
    
    std::ofstream outputFile (outFileName, std::ios::out);
    std::string line, submittedDateTimeStr, submittedDateStr;
    bool skipFirst = true;
    
    if (inputFile.is_open())
    {
        std::getline(inputFile, line);
        skipFirst = (line.find('\"') == std::string::npos); // first line is  header
        
        
        while( inputFile)
        {
            if (skipFirst)
            {
                skipFirst = false;
                outputFile << line << endl;
            }
            else std::getline(inputFile, line);
            
            if (line.length() < 2) continue;
            size_t numberCommas = std::count(line.begin(), line.end(), ',');
            if (numberCommas < 43 ||
                line.find("\"") == std::string::npos ) // skip the header line, which has no "
                continue;
            
            // find the position of the date in the 41st field
            int x = 0;
            //std::string::size_type
            int lastPos=0, startOfDatePos = 0, endOfDatePos = 0;
            int64_t dateIntValue = 0L;
            
            // TODO: make magical 39 to be dateFieldIndex in future refinement
            
            while (x<43   &&  inputFile.good() ) {
                lastPos = (int)line.find(',', lastPos+1);
                if (x== (dateFieldIdx)) // date we seek is in the 41st field
                {
                    startOfDatePos = lastPos+2;
                } else if (startOfDatePos != 0)
                {
                    endOfDatePos = (int)line.find(',', startOfDatePos)-1; // ", is end of field, so -1 for " part
                    break;
                }
                x++;
            }
            
            submittedDateTimeStr = line.substr(startOfDatePos, endOfDatePos-startOfDatePos );  ///19);
            
            // truncate the hours, minutes and seconds off of the date
            submittedDateStr = submittedDateTimeStr.substr(0, submittedDateTimeStr.length()-9 );
            while(submittedDateStr.find('-') != std::string::npos )
                submittedDateStr = submittedDateStr.erase( submittedDateStr.find('-'), 1);
            dateIntValue = std::atol(submittedDateStr.c_str());//, std::locale("en_US.utf-8"));
            
            if (dateIntValue <= bottomCutOffDateValue || dateIntValue >= topCutOffDateValue)
                continue; // skip to the next record if this one is too early or too late
            
            if (outputFile.is_open())
                outputFile << line << endl;
            else
                exit(EXIT_FAILURE);
        }
        inputFile.close();
        outputFile.close();
    }
    return 0;
}


back to top


Appendix B: The Suggested csv Recomposition Schema

This is schema diagram appears in the Donors Choose web site to serve as a diagram for the recomposition of the csv files: back to top

Appendix C: The Data Loader Rewritten in R

This is the last data loader we ended up using.

# This is for display purposes only


# Create function to write data frame to zipped rds file
# The dataframe is split into smaller files depending on size
writeToDisk <- function(df, path) {
  # get the size of the data frame
  filesz = object.size(df)
  
  # Figure out if it needs to be split, we try to 
  # split into sizes ~ 250MB (before compression)
  numsplits = filesz %/% (150*1024*1024)
  
  # Split into subsets and write to disk in RDS format
  # so that we can preserve attritubes including type
  if (numsplits > 1) {
    # Split the dataframe into "numsplits" subsets
    df_split <- split(df, ntile(df$`_projectid`, numsplits))
    
    cat("Writing", numsplits, "files with prefix", path, "\n")
    
    # Save data to separate rds files
    # Wrap loop inside invisible() since we are not interested in
    # the return values
    invisible(lapply(names(df_split), function(x) {
      
      write_rds(df_split[[x]], paste0(path, x, "of", numsplits, ".rds.gz"),
                compress = "gz")
    }))
  }
  else {
    
    cat("Writing 1 file with prefix", path, "\n")
    write_rds(df, paste0(path, ".rds.gz"), compress = "gz")
  }
}

# Create function that download file of type "kind", removes special 
# characters and loads the data
retrieveData <- function(kind, needs_cleanup) {
  
  # Create the download link
  url <- paste0("https://s3.amazonaws.com/open_data/csv/opendata_",
                  kind, ".zip")
     
  # Create the path to download the file to           
  zipname <- paste0("data/opendata_", kind, ".zip")
  
  # Create the filename
  filename <- paste0("opendata_", kind, ".csv")
  
  cat("Downloading from", url, "...")
  
  # Download the file
  download.file(url, zipname)
  
  # Donations, resources and essays data files needed cleanup with
  # special characters, escaped characters etc. creating read errors.
  # Data cleanup was done using sed as a system call after
  # realizing that using pipe() to run sed from R was slow.
  # NOTE: The sed script was created on MacOS and might not be portable.
  # Tried to run sed inside pipe - scan(pipe(sed_cmd), sep = ",") 
  # but had too many issues with needing to use multiple escaped characters
  # Also tried readlines() followed by gsub() but the performance was poor.
  if (needs_cleanup) {
    # cleanup is needed so unzip, run sed and then read in data
    
    # unzip the file
    unzip(zipname, filename)
    
    # Create a sed command to clean out special characters
    sed_cmd <- paste0("sed -i '' -f ", kind,
                      "_clnup.sed ", filename)
    
    cat("Running data cleanup for", filename, "...")
    
    # Run the sed command
    system(sed_cmd)
    
    cat("Loading", kind, "...")
    
    # Read in the data
    assign(kind, read_csv(filename), envir=globalenv())
    
    # Remove files
    unlink(zipname)
    unlink(filename)
  }
  else {
    cat("Loading", kind, "...")
    
    # cleanup is not needed, so read in data directly
    assign(kind, read_csv(unz(zipname, filename)), envir=globalenv())

    # Remove zip file
    unlink(zipname)
  }
}

# Create the list the type of data files we want to download
types_list = c("projects", "resources", "donations", "essays")
  
# Note which files need cleanup
needs_cleanup = c(FALSE, TRUE, TRUE, TRUE)

# Download files, remove special characters and load data
for (index in seq(1:4)) {
  retrieveData(types_list[index], needs_cleanup[index])
}

# Convert dates to "Date" format
projects <- projects %>%
  mutate(date_posted = as_date(date_posted),
         date_completed = as_date(date_completed),
         date_thank_you_packet_mailed =
           as_date(date_thank_you_packet_mailed),
         date_expiration = as_date(date_expiration))

donations <- donations %>%
  mutate(donation_timestamp = as_date(donation_timestamp))

# Filter out projects that were posted in 2014
projects <- projects %>% filter(year(date_posted) == 2014)

# Select resources, donations and essays associated with
# 
resources <- resources %>%
  semi_join(projects, by = "_projectid")
donations <- donations %>%
  semi_join(projects, by = "_projectid")
essays <- essays %>%
  semi_join(projects, by = "_projectid")

# Save filtered data to disk
writeToDisk(df=projects, path="data/opendata_2014_projects")
writeToDisk(df=resources, path="data/opendata_2014_resources")
writeToDisk(df=donations, path="data/opendata_2014_donations")
writeToDisk(df=essays, path="data/opendata_2014_essays")

# Let us clean all the variables so as to be able to start 
# with a clean slate
rm(projects, resources, donations, essays, 
   types_list, needs_cleanup, retrieveData, writeToDisk)

# Cleanup memory
gc()